//
//  PackChildViewController.m
//  IHall
//
//  Created by Soyu on 12-5-14.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "PackChildViewController.h"
#import "DataCenter.h"
#import "PackChildCell.h"
#import "SocketDataHandle.h"
#import "RoomInfoBarView.h"

@interface PackChildViewController ()
{
    
    __weak IBOutlet UIImageView *syLogop;
    __weak IBOutlet UIImageView *sdLogo;
}

@end

@implementation PackChildViewController
@synthesize prckChildTableView;
@synthesize dict;
@synthesize packArray;
@synthesize selectedFoods;
@synthesize sGroupID;
@synthesize food;
@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self)
    {
        // Custom initialization
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    RoomInfoBarView *roomInfobar = [[RoomInfoBarView alloc] initWithXib];
    roomInfobar.frame = CGRectMake(10.0f, 19, roomInfobar.frame.size.width, roomInfobar.frame.size.height);
    [self.view addSubview:roomInfobar];
    
    prckChildTableView.backgroundView = nil;
    prckChildTableView.backgroundColor = [UIColor clearColor];
    prckChildTableView.opaque = NO;
    NSLog(@"dict is %d", dict.count);
    
    if (OEM_FLAG == 1) {
        syLogop.hidden = YES;
        sdLogo.hidden = NO;
    }
    // Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [self setPrckChildTableView:nil];
    sdLogo = nil;
    syLogop = nil;
    [super viewDidUnload];

    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
   return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

- (IBAction)btnCancel:(id)sender
{
    //    [self dismissViewControllerAnimated:YES completion:nil];
    if ([self.delegate respondsToSelector:@selector(packChildViewControllerDiddismiss:)])
    {
        [self.delegate packChildViewControllerDiddismiss:self];
    }
}

- (IBAction)btnOK:(id)sender
{
    for (OKPackChild *pack in packArray)
    {
        if (pack.SelectedCount < pack.SetSumCount.intValue)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"套餐内所选项目未到要求！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
    }

    // 确认后。。。

    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
        @"confirmInputAmount", @"code",
        @"", @"detail",
        nil];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"getDataFromCenter" object:self userInfo:userInfo];
    //    [self.inputViewController dismissModalViewControllerAnimated:YES];
    [self btnCancel:self];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.

    return dict.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self numberOfRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *foodSection = [dict objectForKey:[(OKPackChild *)[self.packArray objectAtIndex:indexPath.section] SetID]];

    OKPackChildFood *foodObj = [foodSection objectAtIndex:indexPath.row];
    OKPackChild     *pack = [self.packArray objectAtIndex:indexPath.section];

    PackChildCell *cell = (PackChildCell *)[tableView dequeueReusableCellWithIdentifier:@"PackChildCell"];

    [cell.btnAdd addTarget:self action:@selector(cellBtnAdd:) forControlEvents:UIControlEventTouchUpInside];
    [cell.btnRemove addTarget:self action:@selector(cellBtnRemove:) forControlEvents:UIControlEventTouchUpInside];
    cell.tag = indexPath.row;
    cell.btnAdd.tag = indexPath.row;
    cell.btnRemove.tag = indexPath.row;
    cell.lblFoodName.text = foodObj.FoodName;

    cell.textLabel.text = foodObj.FoodNo;

    if (foodSection.count == 1)
    {
        cell.lblSelectCount.text = [NSString stringWithFormat:@"%@", pack.SetSumCount];
        cell.stepper.hidden = YES;
        OKFolioObject *folio = [self getSelectedFood:foodObj.FoodNo];

        if (!folio)
        {
            folio = [[OKFolioObject alloc] init];
            folio.FoodNo = foodObj.FoodNo;
            folio.FoodName = foodObj.FoodName;
            folio.Price = @"0";
            folio.Flag = @"N";
            folio.Quantity = cell.lblSelectCount.text.integerValue;
            folio.CanDiscount = @"0";
            folio.Monad = foodObj.Monad;
            folio.IfLowLimitPrice = @"1";
            folio.PrinterNo = foodObj.PrintType;
            folio.OverTimes = foodObj.OverTimes;
            folio.IfPack = @"1";
            folio.IfPackChild = @"1";
            folio.AutoFreed = @"0";
            folio.AutoFreeCount = @"0";
            folio.ParentFoodNo = food.No;
            folio.CanReward = @"0";
            folio.AutoFreeSetIDOfMutilToOne = @"";
            folio.LimitDisRate = @"1";
            folio.SendMobileMsgWhenFree = @"0";
            folio.Note = @"套餐内项目";

            folio.Adds1Name = @"";

            folio.Adds2Name = @"";
            folio.GroupID = sGroupID;
            folio.FlowerGirlsNo = @"";

            [selectedFoods addObject:folio];
        }
    }
    else
    {
        cell.lblSelectCount.text = [NSString stringWithFormat:@"%d", foodObj.SelectedCount];
        cell.stepper.hidden = NO;
    }

    cell.stepper.value = foodObj.SelectedCount;
    cell.stepper.maximumValue = pack.SetSumCount.floatValue - pack.SelectedCount + cell.stepper.value;
    [cell.stepper addTarget:self action:@selector(stepperAction:) forControlEvents:UIControlEventValueChanged];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return ((OKPackChild *)[packArray objectAtIndex:section]).SetItemName;
}

// 分组标题
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    OKPackChild *obj = (OKPackChild *)[self.packArray objectAtIndex:section];
    UIButton    *button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.tag = section;
    [button setBackgroundImage:[UIImage imageNamed:@"SetMeal-05"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(headerClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];

    if (obj.Flag)
    {
        image.image = [UIImage imageNamed:@"SetMeal-03.png"];
        image.transform = CGAffineTransformMakeRotation(1.58);
    }
    else
    {
        image.image = [UIImage imageNamed:@"SetMeal-04.png"];
        image.transform = CGAffineTransformMakeRotation(-1.58);
    }

    [UIView beginAnimations:@"animatecomeout" context:NULL];
    [UIView setAnimationDuration:.25f];

    [UIView commitAnimations];
    [button addSubview:image];

    CGFloat size = 14;
    CGFloat width = [obj.SetItemName sizeWithFont:[UIFont boldSystemFontOfSize:16]].width;

    while (width > 300)
    {
        size -= 1.0;
        width = [obj.SetItemName sizeWithFont:[UIFont boldSystemFontOfSize:--size]].width;
    }

    UILabel *label = [[FXLabel alloc] initWithFrame:CGRectMake(50, 0, width + 300, 40)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    //    label.font = DEFAULT_FONT(18);

    NSArray *array = [dict objectForKey:obj.SetID];

    if (array.count == 1)
    {
        obj.SelectedCount = obj.SetSumCount.integerValue;
    }

    label.text = [NSString stringWithFormat:@"%@|累计可选数量(%@)|已选数量(%d)", obj.SetItemName, obj.SetSumCount, obj.SelectedCount];
    [button addSubview:label];
    return button;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

- (int)numberOfRowsInSection:(NSInteger)section
{
    OKPackChild *group = [self.packArray objectAtIndex:section];

    NSArray *array = [dict objectForKey:group.SetID];

    if (array.count == 1)
    {
        return 1;
    }
    else
    if (group.Flag)
    {
        if (array)
        {
            return array.count;
        }
    }

    return 0;
}

- (void)headerClicked:(id)sender
{
    int         sectionIndex = ((UIButton *)sender).tag;
    OKPackChild *group = [self.packArray objectAtIndex:sectionIndex];

    group.Flag = !group.Flag;

    [self.prckChildTableView reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationTop];
}

- (OKFolioObject *)getSelectedFood:(NSString *)foodNo
{
    for (OKFolioObject *obj in selectedFoods)
    {
        if ([obj.FoodNo isEqualToString:foodNo])
        {
            return obj;
        }
    }

    return nil;
}

- (void)stepperAction:(UIStepper *)sender
{
    NSIndexPath     *ip = [self GetIndexPath:sender];
    NSArray         *foodSection = [dict objectForKey:[(OKPackChild *)[self.packArray objectAtIndex:ip.section] SetID]];
    OKPackChildFood *foodObj = [foodSection objectAtIndex:ip.row];
    OKPackChild     *pack = [self.packArray objectAtIndex:ip.section];

    NSLog(@"sender Value %f", sender.value);

    if ((pack.SelectedCount < pack.SetSumCount.intValue) && (sender.value > foodObj.SelectedCount))
    {
        OKFolioObject *folio = [self getSelectedFood:foodObj.FoodNo];
        [self addFolioObj:folio:foodObj];
        folio.Quantity++;
        pack.SelectedCount++;
        foodObj.SelectedCount++;
        [self.prckChildTableView reloadData];
    }
    else
    {
        pack.SelectedCount--;
        foodObj.SelectedCount--;
        OKFolioObject *folio = [self getSelectedFood:foodObj.FoodNo];
        if (folio)
        {
            folio.Quantity--;
            if (folio.Quantity == 0)
            {
                [selectedFoods removeObject:folio];
            }
        }
        [self.prckChildTableView reloadData];
    }
}

- (void)addFolioObj:(OKFolioObject *)folio:(OKPackChildFood *)foodObj
{
    if (folio == nil)
    {
        folio = [[OKFolioObject alloc] init];
        folio.FoodNo = foodObj.FoodNo;
        folio.FoodName = foodObj.FoodName;
        folio.Price = @"0";
        folio.Flag = @"N";
        folio.Quantity = 1;
        folio.CanDiscount = @"0";
        folio.Monad = foodObj.Monad;
        folio.IfLowLimitPrice = @"1";
        folio.PrinterNo = foodObj.PrintType;
        folio.OverTimes = foodObj.OverTimes;
        folio.IfPack = @"1";
        folio.IfPackChild = @"1";
        folio.AutoFreed = @"0";
        folio.AutoFreeCount = @"0";
        folio.ParentFoodNo = food.No;
        folio.CanReward = @"0";
        folio.AutoFreeSetIDOfMutilToOne = @"";
        folio.LimitDisRate = @"1";
        folio.SendMobileMsgWhenFree = @"0";
        folio.Note = @"套餐内项目";

        folio.Adds1Name = @"";

        folio.Adds2Name = @"";
        folio.GroupID = sGroupID;
        folio.FlowerGirlsNo = @"";
        [selectedFoods addObject:folio];
    }
}

- (NSIndexPath *)GetIndexPath:(id)sender
{
    UIButton        *btn = ((UIButton *)sender);
    UITableViewCell *cell = (UITableViewCell *)[[btn superview] superview];

    return [self.prckChildTableView indexPathForCell:cell];
}

@end
